import Vue from 'vue'
import VueI18n from 'vue-i18n'
import { Locale } from 'vant'
import enUS from 'vant/lib/locale/lang/en-US'
import zhCN from 'vant/lib/locale/lang/zh-CN'
import enLocale from './en'
import zhLocale from './zh'

import { getLStorage } from '@/utils/auth'

Vue.use(VueI18n)

const messages = {
  en: {
    ...enLocale
  },
  zh: {
    ...zhLocale
  }
}

export function setLanguage(lang) {
  if (lang === 'en') {
    Locale.use('en', enUS)
  }
  if (lang === 'zh') {
    Locale.use('zh', zhCN)
  }
}

export function getLanguage() {
  const chooseLanguage = getLStorage('language') || false
  setLanguage(chooseLanguage)
  if (chooseLanguage) return chooseLanguage

  // if has not choose language
  const language = (navigator.language || navigator.browserLanguage).toLowerCase()
  const locales = Object.keys(messages)
  for (const locale of locales) {
    if (language.indexOf(locale) > -1) {
      return locale
    }
  }
  return 'en'
}

const i18n = new VueI18n({
  locale: getLanguage(),
  messages
})

export default i18n

